/**
 * @swagger
 * tags:
 *   name: 题目管理
 *   description: 考试题目相关的接口，包括创建、导入、查询、修改和删除题目
 */

/**
 * @swagger
 * components:
 *   schemas:
 *     QuestionOption:
 *       type: object
 *       required:
 *         - label
 *         - value
 *       properties:
 *         label:
 *           type: string
 *           description: 选项的显示文本
 *           example: "北京是中国的首都"
 *         value:
 *           type: string
 *           description: 选项的值
 *           example: "A"
 *
 *     Question:
 *       type: object
 *       required:
 *         - type
 *         - title
 *       properties:
 *         type:
 *           type: string
 *           description: |
 *             题目类型
 *             * single: 单选题
 *             * multiple: 多选题
 *             * judge: 判断题
 *             * essay: 问答题
 *           enum: [single, multiple, judge, essay]
 *           example: "single"
 *         title:
 *           type: string
 *           description: |
 *             题目标题
 *             * 不能为空
 *           example: "以下哪个说法是正确的？"
 *         content:
 *           type: string
 *           description: |
 *             题目补充内容
 *             * 可选字段
 *             * 可用于添加题目的详细说明或图片链接等
 *           example: "请仔细阅读以下陈述..."
 *         options:
 *           type: array
 *           description: |
 *             题目选项
 *             * 仅用于单选题和多选题
 *             * 至少包含两个选项
 *           items:
 *             $ref: '#/components/schemas/QuestionOption'
 *         correct_answer:
 *           type: string
 *           description: |
 *             正确答案
 *             * 单选题：单个选项值
 *             * 多选题：选项值数组的JSON字符串
 *             * 判断题：'true'或'false'
 *             * 问答题：参考答案（可选）
 *           example: "A"
 *         score:
 *           type: integer
 *           description: |
 *             题目分值
 *             * 必须是非负整数
 *           minimum: 0
 *           example: 5
 *         order_num:
 *           type: integer
 *           description: |
 *             题目顺序号
 *             * 用于自定义题目显示顺序
 *             * 必须是非负整数
 *           minimum: 0
 *           example: 1
 *
 *     ImportQuestions:
 *       type: object
 *       required:
 *         - questions
 *       properties:
 *         questions:
 *           type: array
 *           description: 要导入的题目数组
 *           items:
 *             $ref: '#/components/schemas/Question'
 */

const express = require('express')
const { body, param } = require('express-validator')
const router = express.Router({ mergeParams: true }) // mergeParams allows access to :examId from parent router
const questionController = require('../controllers/questionController')
const { auth, requireRole } = require('../middleware/auth')
const { handleValidationErrors } = require('../middleware/validation')

// 题目验证规则 (用于创建和更新)
const questionValidation = [
  body('type')
    .isIn(['single', 'multiple', 'judge', 'essay'])
    .withMessage("题目类型必须是: 'single', 'multiple', 'judge', 'essay'"),
  body('title').trim().isLength({ min: 1 }).withMessage('题目标题不能为空'),
  body('content').optional().trim(),
  body('options') // For single and multiple choice
    .optional()
    .custom((value, { req }) => {
      if (['single', 'multiple'].includes(req.body.type)) {
        if (!Array.isArray(value) || value.length < 2) {
          throw new Error('选择题的选项必须是至少包含两个元素的数组')
        }
        // Optionally validate structure of options: value.every(opt => typeof opt.label === 'string' && typeof opt.value === 'string')
      }
      return true
    }),
  body('correct_answer').custom((value, { req }) => {
    if (
      req.body.type === 'essay' &&
      value !== undefined &&
      value !== null &&
      value !== ''
    ) {
      // For essay, correct_answer might be a model answer, or not strictly required at creation
      // return true;
    } else if (
      req.body.type !== 'essay' &&
      (value === undefined || value === null || value === '')
    ) {
      throw new Error('非简答题的正确答案不能为空')
    }
    // Further validation for 'single', 'multiple', 'judge' can be added here
    // e.g., for 'judge', correct_answer should be 'true' or 'false' (or 0/1)
    // for 'multiple', correct_answer should be an array of strings/numbers
    return true
  }),
  body('score')
    .optional()
    .isInt({ min: 0 }) // Allow 0 score
    .withMessage('分数必须是非负整数'),
  body('order_num')
    .optional()
    .isInt({ min: 0 })
    .withMessage('题目顺序号必须是非负整数'),
]

// 批量导入题目验证规则
const importQuestionsValidation = [
  body('questions')
    .isArray({ min: 1 })
    .withMessage('导入的题目必须是一个至少包含一个题目的数组'),
  body('questions.*.type')
    .isIn(['single', 'multiple', 'judge', 'essay'])
    .withMessage('每个题目的类型无效'),
  body('questions.*.title')
    .trim()
    .isLength({ min: 1 })
    .withMessage('每个题目的标题不能为空'),
  body('questions.*.score')
    .optional()
    .isInt({ min: 0 })
    .withMessage('每个题目的分数必须是非负整数'),
  // Add more specific validations for options and correct_answer based on type if needed
]

// 路由定义 (所有路由都将基于 /api/exams/:examId/questions)
// 管理员操作
router.post(
  '/',
  auth,
  requireRole(['admin']),
  param('examId').isInt().withMessage('考试ID必须是整数'),
  questionValidation,
  handleValidationErrors,
  questionController.createQuestion
)
router.post(
  '/import',
  auth,
  requireRole(['admin']),
  param('examId').isInt().withMessage('考试ID必须是整数'),
  importQuestionsValidation,
  handleValidationErrors,
  questionController.importQuestions
)

// 学生和管理员均可获取题目列表 (学生获取时答案可能被过滤)
router.get(
  '/',
  auth,
  param('examId').isInt().withMessage('考试ID必须是整数'),
  handleValidationErrors,
  questionController.getQuestions
)

// 管理员操作
router.put(
  '/:questionId',
  auth,
  requireRole(['admin']),
  param('examId').isInt().withMessage('考试ID必须是整数'), // Though not directly used by controller, good for consistency
  param('questionId').isInt().withMessage('题目ID必须是整数'),
  questionValidation,
  handleValidationErrors,
  questionController.updateQuestion
)
router.delete(
  '/:questionId',
  auth,
  requireRole(['admin']),
  param('examId').isInt().withMessage('考试ID必须是整数'),
  param('questionId').isInt().withMessage('题目ID必须是整数'),
  handleValidationErrors,
  questionController.deleteQuestion
)

module.exports = router

/**
 * @swagger
 * /api/exams/{examId}/questions:
 *   post:
 *     summary: 创建新题目
 *     description: |
 *       在指定考试中创建新的题目
 *       * 仅管理员可操作
 *       * 支持多种题型：单选、多选、判断、问答
 *       * 选择题需提供选项数组
 *     tags: [题目管理]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: examId
 *         required: true
 *         description: 考试ID
 *         schema:
 *           type: integer
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/Question'
 *     responses:
 *       201:
 *         description: 题目创建成功
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/Question'
 *       400:
 *         description: |
 *           输入验证错误
 *           * 必填字段缺失
 *           * 题目类型无效
 *           * 选项格式错误
 *       401:
 *         description: 未授权访问
 *       403:
 *         description: 权限不足，需要管理员权限
 */

/**
 * @swagger
 * /api/exams/{examId}/questions/import:
 *   post:
 *     summary: 批量导入题目
 *     description: |
 *       批量导入多个题目到指定考试
 *       * 仅管理员可操作
 *       * 支持一次导入多个不同类型的题目
 *       * 所有题目必须符合格式要求
 *     tags: [题目管理]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: examId
 *         required: true
 *         description: 考试ID
 *         schema:
 *           type: integer
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/ImportQuestions'
 *     responses:
 *       201:
 *         description: 题目批量导入成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 imported_count:
 *                   type: integer
 *                   description: 成功导入的题目数量
 *       400:
 *         description: |
 *           输入验证错误
 *           * 题目数组为空
 *           * 题目格式错误
 *       401:
 *         description: 未授权访问
 *       403:
 *         description: 权限不足，需要管理员权限
 */

/**
 * @swagger
 * /api/exams/{examId}/questions:
 *   get:
 *     summary: 获取题目列表
 *     description: |
 *       获取指定考试的所有题目
 *       * 需要登录才能访问
 *       * 学生用户获取时答案会被过滤
 *       * 支持按题型筛选
 *     tags: [题目管理]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: examId
 *         required: true
 *         description: 考试ID
 *         schema:
 *           type: integer
 *     responses:
 *       200:
 *         description: 成功获取题目列表
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 $ref: '#/components/schemas/Question'
 *       401:
 *         description: 未授权访问
 *       404:
 *         description: 考试不存在
 */

/**
 * @swagger
 * /api/exams/{examId}/questions/{questionId}:
 *   put:
 *     summary: 更新题目
 *     description: |
 *       更新指定题目的信息
 *       * 仅管理员可操作
 *       * 可以修改题目的所有属性
 *       * 不能更改题目类型
 *     tags: [题目管理]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: examId
 *         required: true
 *         description: 考试ID
 *         schema:
 *           type: integer
 *       - in: path
 *         name: questionId
 *         required: true
 *         description: 题目ID
 *         schema:
 *           type: integer
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/Question'
 *     responses:
 *       200:
 *         description: 题目更新成功
 *       400:
 *         description: |
 *           输入验证错误
 *           * 必填字段缺失
 *           * 格式错误
 *       401:
 *         description: 未授权访问
 *       403:
 *         description: 权限不足，需要管理员权限
 *       404:
 *         description: 题目不存在
 *
 *   delete:
 *     summary: 删除题目
 *     description: |
 *       删除指定的题目
 *       * 仅管理员可操作
 *       * 删除后不可恢复
 *       * 如果题目已被作答，建议不要删除
 *     tags: [题目管理]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: examId
 *         required: true
 *         description: 考试ID
 *         schema:
 *           type: integer
 *       - in: path
 *         name: questionId
 *         required: true
 *         description: 题目ID
 *         schema:
 *           type: integer
 *     responses:
 *       200:
 *         description: 题目删除成功
 *       401:
 *         description: 未授权访问
 *       403:
 *         description: 权限不足，需要管理员权限
 *       404:
 *         description: 题目不存在
 */
